//
//  HealthyViewController.m
//  B
//
//  Created by lanou on 16/5/14.
//  Copyright © 2016年 裴启航. All rights reserved.
//

#import "HealthyViewController.h"
@import HealthKit;

@interface HealthyViewController ()<UITextFieldDelegate>
@property (nonatomic) HKHealthStore *healthStore;
@property (weak, nonatomic) IBOutlet UILabel *readStepLabel; // 展示系统的步数
@property (weak, nonatomic) IBOutlet UITextField *Sheight; // 身高
@property (weak, nonatomic) IBOutlet UITextField *Tkg; // 体重
@property (weak, nonatomic) IBOutlet UITextField *Result;

@property (weak, nonatomic) IBOutlet UILabel *nowDate;
@end

@implementation HealthyViewController
- (void)viewWillAppear:(BOOL)animated {
    self.navigationController.navigationBar.tintColor = [UIColor grayColor];
    //修改导航条标题颜色
    self.navigationItem.title = @"健康指数";
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor grayColor],NSForegroundColorAttributeName,nil]];
}
- (void)viewWillDisappear:(BOOL)animated {
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],NSForegroundColorAttributeName,nil]];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    //查看healthKit在设备上是否可用，ipad不支持HealthKit
    if(![HKHealthStore isHealthDataAvailable])
    {
        NSLog(@"设备不支持healthKit");
    }
    //创建healthStore实例对象
    self.healthStore = [[HKHealthStore alloc] init];
    //设置需要获取的权限这里仅设置了步数
    HKObjectType *stepCount = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
    
    NSSet *healthSet = [NSSet setWithObjects:stepCount, nil];
    
    //从健康应用中获取权限
    [self.healthStore requestAuthorizationToShareTypes:nil readTypes:healthSet completion:^(BOOL success, NSError * _Nullable error) {
        if (success)
        {
            NSLog(@"获取步数权限成功");
            //获取步数后我们调用获取步数的方法
            [self readStepCount];
        }
        else
        {
            NSLog(@"获取步数权限失败");
        }
    }];
    _Sheight.delegate = self;
    _Tkg.delegate = self;
}
- (void)textFieldDidEndEditing:(UITextField *)textField {
    [self changeNum];
    [self.view endEditing:YES];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self changeNum];
    [self.view endEditing:YES];
}
- (void)changeNum {
    if (![self isBlankString:_Sheight.text] && ![self isBlankString:_Tkg.text]) {
        CGFloat num = _Tkg.text.floatValue / (_Sheight.text.floatValue * _Sheight.text.floatValue * 0.01 * 0.01) * 1.0;
        _Result.text = [NSString stringWithFormat:@"%.2f", num];
    }
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string;
{ //string就是此时输入的那个字符textField就是此时正在输入的那个输入框返回YES就是可以改变输入框的值NO相反
    if ([string isEqualToString:@"\n"]) { //按会车可以改变
        return YES;
    }
    NSString * toBeString = [textField.text stringByReplacingCharactersInRange:range withString:string]; //得到输入框的内容
    if (_Sheight == textField | _Tkg == textField) {//判断是否时我们想要限定的那个输入框
        if (toBeString.length > 3) {
            textField.text = [toBeString substringToIndex:3];
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"超过最大字数不能输入了" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
            [alert show];
            return NO;
        }
    }
    return YES;
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField {
    return YES;
}
//查询数据
- (void)readStepCount
{
    //查询采样信息
    HKSampleType *sampleType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
    //NSSortDescriptors用来告诉healthStore怎么样将结果排序。
    NSSortDescriptor *start = [NSSortDescriptor sortDescriptorWithKey:HKSampleSortIdentifierStartDate ascending:NO];
    NSSortDescriptor *end = [NSSortDescriptor sortDescriptorWithKey:HKSampleSortIdentifierEndDate ascending:NO];
    /*查询的基类是HKQuery，这是一个抽象类，能够实现每一种查询目标，这里我们需要查询的步数是一个
     HKSample类所以对应的查询类就是HKSampleQuery。
     下面的limit参数传1表示查询最近一条数据,查询多条数据只要设置limit的参数值就可以了
     */
    HKSampleQuery *sampleQuery = [[HKSampleQuery alloc] initWithSampleType:sampleType predicate:nil limit:1 sortDescriptors:@[start,end] resultsHandler:^(HKSampleQuery * _Nonnull query, NSArray<__kindof HKSample *> * _Nullable results, NSError * _Nullable error) {
        //打印查询结果
//        NSLog(@"resultCount = %lu result = %@",results.count,results);
        if (results.count == 0) {
            _readStepLabel.text = @"0";
            return;
        }
        //把结果装换成字符串类型
        HKQuantitySample *result = results[0];
//        // 获取手机型号
//        NSString *version = result.device.hardwareVersion;
        HKQuantity *quantity = result.quantity;
        double value = [quantity doubleValueForUnit:[HKUnit countUnit]];
        
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            //查询是在多线程中进行的，如果要对UI进行刷新，要回到主线程中
            NSLog(@"最新步数：%f",value);
            _readStepLabel.text = [NSString stringWithFormat:@"%.f", value];
            _nowDate.text = [NSString stringWithFormat:@"更新与%@", result.endDate];
        }];
    }];
    //执行查询
    [self.healthStore executeQuery:sampleQuery];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
